#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>

int main()
{
  int pipefd[2] = {0};
  if(pipe(pipefd) != 0)
  {
    perror("pipe error");
    return 1;
  }
  printf("pipefd[0]: %d\n", pipefd[0]);//3
  printf("pipefd[1]: %d\n", pipefd[1]);//4
  
  /*现在我们让父进程读取，子进程写入*/
  if(fork()==0)
  {
    //child
    close(pipefd[0]);
    const char* msg = "余下的路还有好长~";
    while(1)
    {
      write(pipefd[1], msg, strlen(msg));
    }
    exit(0);
  }
  //father
  close(pipefd[1]);
  while(1)
  {
    char buffer[64] = {0}; //清空缓冲区~
    ssize_t s = read(pipefd[0], buffer, sizeof(buffer)-1);
    if(s == 0)
    {
      printf("writer quit...\n");
      break;
    }
    else if(s > 0)
    {
      buffer[s]=0; //字符串儿结束
      printf("child said to father# %s\n",buffer);
    }
    else 
    {
      printf("read error...\n");
      break;
    }
    printf("reader is going to leave...\n");
    sleep(5);
    break; 
  }
  close(pipefd[0]);
  int status = 0;
  waitpid(-1, &status, 0);
  printf("exit code: %d\n", (status>>8)&0xFF); 
  printf("signal: %d\n", status&0x7F);
  return 0;
}
